﻿using CommandService;
using Entity;
using Entity.FrameEntity;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using SysFramework;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using Tools;
using System.Net.WebSockets;
using System.Collections.Immutable;
using System.Threading.Tasks.Dataflow;

namespace BLL
{
    public class BasicBLL : PubMethod
    {
        ReturnResult rsl;
        Commands cmd;
        SystemManagement sysBLL;
        OperateModel oper;
        List<OperateModel> operList;
        public BasicBLL()
        {
            rsl = new ReturnResult();
            cmd = new Commands();
            sysBLL = new SystemManagement();
        }
        /// <summary>
        /// 通用数据获取方法
        /// </summary>
        /// <param name="type">类型编码</param>
        /// <returns></returns>
        public ReturnResult GetCommonData(string type)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_CommonData_Info where");
                sb.Append(" isdel=0 and parentCode='" + type + "' and status='Y' and cValues='3'");
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0)
                {
                    rsl.Data = cmd.TableToDictionary(table);
                    rsl.Result = true;
                }
                else
                {
                    rsl.Message = "没有数据";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

  
        public ReturnResult GetGongXuMachine(string gxCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select cCode,cName from fun_CommonData_Info where");
                sb.Append(" isdel=0 and parentCode='scjt' and status='Y' and cValues='3' and cMemo='"+ gxCode +"'");
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0)
                {
                    rsl.Data = cmd.TableToDictionary(table);
                    rsl.Result = true;
                }
                else
                {
                    rsl.Message = "没有数据";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        public ReturnResult CommonDataTree(string dataType, string baseCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_CommonTree_info where trType='" + dataType + "'");
                sb.Append(" and isdel=0 and baseCode='" + baseCode + "' ");
                sb.Append(" or (parentCode is null and trType='" + dataType + "')");
                var table = cmd.GetDataTable(sb.ToString());//获取全部有效菜单信息

                List<Dictionary<string, object>> menuList = new List<Dictionary<string, object>>();
                #region 构建数据
                var fMenu = table.Select("parentCode is null or parentCode=''");//获取所有父级菜单
                for (int i = 0; i < fMenu.Length; i++)
                {
                    var fdic = new Dictionary<string, object>();
                    fdic["title"] = string.Format("{0}({1})", fMenu[i]["trName"].ToString(), fMenu[i]["trCode"].ToString());
                    fdic["id"] = fMenu[i]["trCode"].ToString();
                    fdic["spread"] = "true";

                    #region 子菜单
                    List<Dictionary<string, object>> cList = new List<Dictionary<string, object>>();
                    this.ChildUrl(table, fMenu[i]["trCode"].ToString(), ref cList);
                    fdic["children"] = cList;
                    #endregion
                    menuList.Add(fdic);
                }
                #endregion
                rsl.Data = menuList;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        private void ChildUrl(DataTable table, string cCode, ref List<Dictionary<string, object>> chlist)
        {
            var dr = table.Select("parentCode='" + cCode + "'");
            if (dr.Length > 0)
            {
                for (int x = 0; x < dr.Length; x++)
                {
                    List<Dictionary<string, object>> tempList = new List<Dictionary<string, object>>();
                    var cdic = new Dictionary<string, object>();
                    cdic["title"] = string.Format("{0}({1})", dr[x]["trName"].ToString(), dr[x]["trCode"].ToString());
                    cdic["id"] = dr[x]["trCode"].ToString();
                    ChildUrl(table, dr[x]["trCode"].ToString(), ref tempList);
                    // cdic["spread"] = "true";
                    cdic["children"] = tempList;
                    chlist.Add(cdic);
                }
            }
        }
        /// <summary>
        /// 获取出入库状态
        /// </summary>
        /// <param name="types"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getDictionaryInfo(string types, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                string sql = "select code value,name from sys_dictionaries_info where types='" + types + "' and status=1 ";
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    sql = sql + condition;
                }
                var t = cmd.GetDataTable(sql);
                rsl.Data = cmd.TableToDictionary(t);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        
        /// <summary>
        /// 获取生产工序
        /// </summary>
        /// <param name="types"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getCommonDataInfo(string types, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                string sql = "select cCode,cName from fun_CommonData_Info where cType='" + types + "' and status = 'Y' and isDel = 0 ";
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    sql = sql + condition;
                }
                var t = cmd.GetDataTable(sql);
                rsl.Data = cmd.TableToDictionary(t);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 通用数据数据大类
        /// </summary>
        /// <param name="type">数据类型编码</param>
        /// <returns></returns>
        public ReturnResult getCommonDataTop()
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select cCode,cName from fun_CommonData_Info where isDel=0");
                sb.Append(" and parentCode = '0' and status = 'Y' ");
                rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 通用数据数据类型
        /// </summary>
        /// <param name="type">数据类型编码</param>
        /// <returns></returns>
        public ReturnResult getCommonDataType(string type)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select distinct cCode,cName from fun_CommonData_Info where isdel=0");
                sb.Append(" and status='Y' and cvalues='2'");
                if (!string.IsNullOrWhiteSpace(type))
                {
                    sb.Append(" and parentCode='" + type + "'");
                }
                rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 系统通用数据添加方法
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult UpdateCommonData(string userCode, string datas)
        {
            rsl = new ReturnResult();
            try
            {
                oper = new OperateModel();
                var data = JsonConvert.DeserializeObject<DbCommonData>(datas);
               var sql = "select * from fun_CommonData_Info where cCode='" + data.cCode + "'";
                var table = cmd.GetDataTable(sql);
         
                if (data.id == null || data.id == 0)
                {
                    if (table.Rows.Count > 0)
                    {
                        rsl.Message = "编码存在重复";
                        return rsl;
                    }
                    if (data.cType ==data.parentCode)
                    {
                        data.cValues = "2";
                    }
                    else
                    {
                        data.cValues = "3";
                    }
                    data.isDel = 0;
                    data.status = "Y";
                    data.isSys = "0";
                    data.createtime = getNow();
                    data.createuser = userCode;
                    rsl = cmd.Add(data);

                }
                else
                {
                    foreach(DataRow r in table.Rows)
                    {
                        if (r["id"].ToString() != data.id.ToString())
                        {
                            rsl.Message = "编码存在重复";
                            return rsl;
                         
                        }
                     
                    }
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                    oper.Data = data;
                    rsl = cmd.Edit(oper);
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 通用数据列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getCommonDataList(string baseCode, string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                var arr = condition.Split(',');
                StringBuilder sb = new StringBuilder();
                sb.Append(" status='Y' and isdel=0 and parentCode='" + arr[0] + "'");
                sb.Append("and cValues='3'");
                var list = cmd.PageList("fun_CommonData_Info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 版辊列表
        /// </summary>
        /// <param name="baseCode"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult GetBanGunList(string pageIndex, string pageSize, string condition,string isAdmin,string baseCode,ref string pageCount)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(" isdel=0 ");
                if (isAdmin != "1")
                {
                    sb.Append(" and baseCode='"+ baseCode +"'");
                }
                sb = this.CreateSelectCondition(sb,condition);
                var list = cmd.PageList("V_fun_BanYangInfo", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 删除共用数据方法
        /// </summary>
        /// <param name="dataId">数据id</param>
        /// <returns></returns>
        public ReturnResult DelCommonData(string userCode, string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                oper = new OperateModel();
                DbCommonData data = new DbCommonData();
                data.id = int.Parse(dataId);
                data.isDel = 1;
                data.delMsg =string.Format("{0}({1})", userCode, getNow());
                oper.Data = data;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "id";
                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 根据id获取通用数据
        /// </summary>
        /// <param name="dataId">数据id</param>
        /// <returns></returns>
        public ReturnResult getCommonDataById(string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_CommonData_Info where ");
                sb.Append("id=" + dataId);
                rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 通用数据单元格修改事件
        /// </summary>
        /// <param name="id"></param>
        /// <param name="values"></param>
        /// <returns></returns>
        public ReturnResult EditCommonNames(string id, string values)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(values))
                {
                    rsl.Message = "修改内容不允许为空";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("update fun_CommonData_Info set cName='" + values + "' where ");
                sb.Append("id=" + id);
                rsl = cmd.UpdateSql(sb.ToString());
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        #region 客商大类树结构参数
        ///// <summary>
        ///// 客商大类树结构参数
        ///// </summary>
        ///// <returns></returns>
        //public ReturnResult venCustomClass(string baseCode,string trType)
        //{
        //    rsl = new ReturnResult();
        //    try
        //    {
        //        StringBuilder sb = new StringBuilder();
        //        sb.Append("select * from fun_CommonTree_info ");
        //        sb.Append(" where trType = '" + trType + "' and isdel=0 and baseCode='" + baseCode + "'");
        //        //sb.Append(" or cCode='0'");
        //        var table = cmd.GetDataTable(sb.ToString());//获取全部有效菜单信息

        //        List<Dictionary<string, object>> menuList = new List<Dictionary<string, object>>();
        //        #region 构建数据
        //        var fMenu = table.Select("parentCode is null");//获取所有父级菜单
        //        for (int i = 0; i < fMenu.Length; i++)
        //        {
        //            var fdic = new Dictionary<string, object>();
        //            fdic["title"] = string.Format("{0}({1})", fMenu[i]["cName"].ToString(), fMenu[i]["cCode"].ToString());
        //            fdic["id"] = fMenu[i]["cCode"].ToString();
        //            fdic["spread"] = "true";

        //            #region 子菜单
        //            List<Dictionary<string, object>> cList = new List<Dictionary<string, object>>();
        //            this.ChildUrl(table, fMenu[i]["cCode"].ToString(), ref cList);
        //            fdic["children"] = cList;
        //            #endregion
        //            menuList.Add(fdic);
        //        }
        //        #endregion
        //        rsl.Data = menuList;
        //        rsl.Result = true;
        //    }
        //    catch (Exception ex)
        //    {
        //        rsl.Message = ex.Message;
        //    }
        //    return rsl;
        //}
        ///// <summary>
        ///// 子菜单生成方法(递归)
        ///// </summary>
        ///// <param name="table"></param>
        ///// <param name="cCode"></param>
        ///// <param name="menuName"></param>
        ///// <param name="icon"></param>
        ///// <param name="chlist"></param>
        //private void ChildUrl(DataTable table, string cCode, ref List<Dictionary<string, object>> chlist)
        //{
        //    var dr = table.Select("parentCode='" + cCode + "'");
        //    if (dr.Length > 0)
        //    {
        //        for (int x = 0; x < dr.Length; x++)
        //        {
        //            List<Dictionary<string, object>> tempList = new List<Dictionary<string, object>>();
        //            var cdic = new Dictionary<string, object>();
        //            cdic["title"] = string.Format("{0}({1})", dr[x]["cName"].ToString(), dr[x]["cCode"].ToString());
        //            cdic["id"] = dr[x]["cCode"].ToString();
        //            ChildUrl(table, dr[x]["cCode"].ToString(), ref tempList);
        //            // cdic["spread"] = "true";
        //            cdic["children"] = tempList;
        //            chlist.Add(cdic);
        //        }
        //    }
        //}
        #endregion

      

        /// <summary>
        /// 获取存货BOM信息
        /// </summary>
        /// <param name="proCode">存货编码</param>
        /// <returns></returns>
        public ReturnResult GetProductBOMCode(string proCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(proCode))
                {
                    rsl.Message = "存货编码不允许为空";
                    return rsl;
                }

                var dic = new Dictionary<string, string>();

                sb.Append("seleCt bomCode from bom_ProductionBom_main ");
                sb.Append(" where isdel=0 and relationType='pro' and relationCode='" + proCode + "'");
                sb.Append(" order by bomVersion desc ");
                var table = cmd.GetDataTable(sb.ToString());

                if (table.Rows.Count > 0)
                {
                    dic["bomCode"] = table.Rows[0][0].ToString();
                    rsl.Result = true;
                    rsl.Data = dic;
                }
                else
                {
                    rsl.Message = "没有bom数据";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 查询Bom信息
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <param name="baseCode"></param>
        /// <returns></returns>
        public ReturnResult GetBomMainList(string pageIndex, string pageSize, string condition,string baseCode, ref string pageCount )
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(" isdel=0 ");
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                sb = CreateSelectCondition(sb, condition);
                var list = cmd.PageList("V_BomMain_list", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount, "");
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 查询Bom原辅料列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="bomCode"></param>
        /// <param name="baseCode"></param>
        /// <returns></returns>
        public ReturnResult GetBomMaterialList(string pageIndex, string pageSize, ref string pageCount, string bomCode, string baseCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(" isdel=0 and materialType='meterial' and bomCode='"+ bomCode + "'");
                var list = cmd.PageList("V_BomSub_meterial", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount, "");
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// bom版辊
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="bomCode"></param>
        /// <param name="pageCount"></param>
        /// <returns></returns>
        public ReturnResult GetBomBanGun(string pageIndex, string pageSize, string bomCode, ref string pageCount)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(" isdel=0 and materialType='bangun' and bomCode='" + bomCode + "'");
                var list = cmd.PageList("V_BomSub_BanGun", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount, "");
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// bom信息保存
        /// </summary>
        /// <param name="datas">数据</param>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult UpdateBomData(string datas,string userCode)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            operList = new List<OperateModel>();
            try
            {
                var obj = JsonConvert.DeserializeObject<DbBomMain>(datas);
                DataTable gyTable = new DataTable();
                if (string.IsNullOrWhiteSpace(obj.relationCode))
                {
                    rsl.Message = "bom关联存货不允许为空"; return rsl;
                }
                sb.Append(" select * from bom_ProductionBom_main ");
                sb.Append(" where isdel = 0 and relationCode = '" + obj.relationCode + "' ");//是否已经存在存货BOM
                var table = cmd.GetDataTable(sb.ToString());
                
                oper = new OperateModel();
          
                if (obj.id == 0 || obj.id == null)
                {
                    if (table.Rows.Count > 0)
                    {
                        rsl.Message = "该存货只允许存在一个BOM"; return rsl;
                    }
                    obj.bomCode = getTimeString();
                    obj.relationType = "Pro";
                    obj.isdel = 0;
                    obj.createtime = getNow();
                    obj.createuser = userCode;
                    oper.Types=OperateModel.OperateType.Add;
                }
                else
                {
                    if (table.Rows.Count > 0 && table.Rows[0]["id"].ToString()!=obj.id.ToString())
                    {
                        rsl.Message = "该存货只允许存在一个BOM"; return rsl;
                    }
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                }
                oper.Data = obj;
                operList.Add(oper);
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                    if (rsl.Result)
                    {
                        rsl.Data = obj.bomCode;
                    }
                }
                else
                {
                    rsl.Message = "没有数据"; return rsl;
                }


            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取存货关联版辊信息
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="bomCode"></param>
        /// <param name="baseCode"></param>
        /// <returns></returns>
        public ReturnResult GetBabGunByCode(string pageIndex, string pageSize, string condition,ref string pageCount)
        {
            rsl = new ReturnResult();
            try
            {
                var obj = JsonConvert.DeserializeObject<JObject>(condition);
                StringBuilder sb = new StringBuilder();
                sb.Append(" isdel=0 and proCode='"+ obj["proCode"].ToString() + "'");
                var list = cmd.PageList("V_fun_BanYangPro", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount, "");
                sb.Clear();
                sb.Append("select materialCode from bom_ProductionBom_sub where isdel=0 and materialType='bangun'");
                var bgTable = cmd.GetDataTable(sb.ToString());
                for (int i=0;i<list.Count;i++)
                {
                    var dr = bgTable.Select("materialCode='"+ list[i]["byBarCode"] +"'");
                    if (dr.Length > 0)
                    {
                        list[i]["isUsed"] = "1";
                    }
                    else {
                        list[i]["isUsed"] = "0";
                    }
                }
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        public ReturnResult EditBomSunMaterial(string dataId,string fieldName,string fieldValue)
        { 
            rsl=new ReturnResult();
            try
            {
                if (!string.IsNullOrWhiteSpace(fieldValue))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("update bom_ProductionBom_sub set " + fieldName + "='" + fieldValue + "'");
                    sb.Append(" where id=" + dataId);
                    rsl = cmd.UpdateSql(sb.ToString());
                }
                else
                {
                    rsl.Message = "信息填写不完整";
                }
            }
            catch (Exception ex)
            { 
            rsl.Message=ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取存货关联版辊样版信息
        /// </summary>
        /// <param name="type">类型编码</param>
        /// <returns></returns>
        public ReturnResult GetByBarCode(string type)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_BanYang_list where");
                sb.Append(" isdel=0 and proCode='" + type + "'");
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0)
                {
                    rsl.Data = cmd.TableToDictionary(table);
                    rsl.Result = true;
                }
                else
                {
                    rsl.Message = "没有数据";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 保存版辊存货数据对应关系
        /// </summary>
        /// <param name="datas">数据</param>
        /// <param name="userCode">人员</param>
        /// <returns></returns>
        public ReturnResult SaveBanGunPro(string datas,string userCode)
        { 
            rsl=new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                if (string.IsNullOrWhiteSpace(json["proCode"].ToString()))
                {
                    rsl.Message = "关联存货不允许为空";return rsl;
                }
                if (string.IsNullOrWhiteSpace(json["barCodes"].ToString()))
                {
                    rsl.Message = "关联版辊不允许为空"; return rsl;
                }
                #region 版辊、存货对应数据保存
                DbBanYangPro byp;
                var pArr = json["proCode"].ToString().Split(',');
                var bArr = json["barCodes"].ToString().Split(',');
                foreach (var p in pArr)
                {
                    if (!string.IsNullOrWhiteSpace(p))
                    {
                        foreach (string b in bArr)
                        {
                            if (!string.IsNullOrWhiteSpace(b))
                            {
                                string sql = "select id from fun_BanYang_pro where proCode='" + p + "' and byBarCode='" + b + "' and isdel=0";
                                var qTable = cmd.GetDataTable(sql);
                                if (qTable.Rows.Count > 0)
                                {
                                    rsl.Message = "该存货、版辊信息已配置，版辊：" + b; return rsl;
                                }
                                byp = new DbBanYangPro();
                                byp.id = Guid.NewGuid().ToString().Replace("-", "");
                                byp.byBarcode = b;
                                byp.proCode = p;
                                byp.createuser = userCode;
                                byp.createtime = getNow();
                                byp.isdel = 0;
                                oper=new OperateModel();
                                oper.Data = byp;
                                oper.Types = OperateModel.OperateType.Add;
                                operList.Add(oper);
                            }
                        }
                    }
                }
                #endregion

                #region 改变关联样版状态   注释
                DbBanGun bg;
                foreach (string b in bArr)
                {
                    if (!string.IsNullOrWhiteSpace(b))
                    {
                        bg = new DbBanGun();
                        bg.byBarCode = b;
                        bg.proCode = json["proCode"].ToString();
                        oper = new OperateModel();
                        oper.Data = bg;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "byBarCode";
                        operList.Add(oper);
                    }
                }
                #endregion
                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取版辊/样版存货详细信息
        /// </summary>
        /// <param name="byBarCode"></param>
        /// <returns></returns>
        public ReturnResult GetBanYangDetails(string byBarCode)
        { 
            rsl= new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select b.*,p.proName,p.spec from fun_BanYang_pro b inner join fun_Inventory_Info p");
                sb.Append(" on b.proCode=p.proCode where b.isdel=0 and b.byBarCode='"+ byBarCode +"'");
                rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Result = true;
            }
            catch (Exception ex)
            { 
            rsl.Message=ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 删除样版/版辊与存货的对应关系
        /// </summary>
        /// <param name="dataId">数据id</param>
        /// <param name="byBarCode">版辊编码</param>
        /// <param name="userCode">人员账号</param>
        /// <returns></returns>
        public ReturnResult DelBanYangPro(string dataId,string byBarCode,string userCode)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {

                DbBanYangPro db = new DbBanYangPro();
                db.id= dataId;
                db.isdel = 1;
                db.delMsg = string.Format("{0}({1})",userCode,getNow());
                oper=new OperateModel();
                oper.Data = db;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "id";
                operList.Add(oper);
                #region 判断版辊是否存在其他存货使用，不存在则改变版辊状态
                StringBuilder sb = new StringBuilder();
                sb.Append("select id from fun_BanYang_pro where byBarCode='"+ byBarCode + "' and isdel=0");
                var qTable = cmd.GetDataTable(sb.ToString());
                if (qTable.Rows.Count < 2)
                { 
                    DbBanGun dbBanGun = new DbBanGun();
                    dbBanGun.proCode = "-";
                    dbBanGun.byBarCode = byBarCode;
                    oper = new OperateModel();
                    oper.Data = dbBanGun;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "byBarCode";
                    operList.Add(oper);
                }
                #endregion
                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 根据bom编码获取bom信息
        /// </summary>
        /// <param name="bomCode"></param>
        /// <returns></returns>
        public ReturnResult GetBomMainByCode(string bomCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select m.*,p.proName,p.spec from bom_ProductionBom_main m");
                sb.Append(" inner join fun_Inventory_Info p on m.relationCode=p.proCode");
                sb.Append(" where m.bomCode='"+ bomCode +"'");
                rsl.Result = true;
                rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
            }
            catch (Exception ex)
            { 
            rsl.Message= ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// bom子表数据保存
        /// </summary>
        /// <param name="proCodes"></param>
        /// <param name="bomCode"></param>
        /// <param name="dType"></param>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult AddBomSubDatas(string proCodes, string bomCode,string dType,string userCode)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                if (string.IsNullOrWhiteSpace(proCodes))
                {
                    rsl.Message = "保存数据丢失";return rsl;
                }
                if (string.IsNullOrWhiteSpace(proCodes))
                {
                    rsl.Message = "bom数据丢失"; return rsl;
                }
                string sql = "select * from bom_ProductionBom_sub where bomCode='"+ bomCode + "' and isdel=0 and materialType='"+ dType + "'";
                var bTable = cmd.GetDataTable(sql);
                DbBomSub bms;
                var pArr=proCodes.Split(',');
                foreach (string s in pArr)
                {
                    if (!string.IsNullOrWhiteSpace(s))
                    {
                        //var dr = bTable.Select("materialCode='"+ s +"'");
                        //if (dr.Length > 0)
                        //{
                        //    rsl.Message = "禁止添加重复数据"; return rsl;
                        //}
                        bms = new DbBomSub();
                        bms.materialCode = s;
                        bms.bomCode = bomCode;
                        bms.unitCode = "kg";
                        bms.number = "0";
                        bms.standardNum = "1";
                        bms.materialType= dType;
                        bms.isdel = 0;
                        bms.createtime = getNow();
                        bms.createuser=userCode;
                        oper = new OperateModel();
                        oper.Data= bms;
                        oper.Types = OperateModel.OperateType.Add;
                        operList.Add(oper);
                    }
                }
                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 根据id删除bom子表数据方法
        /// </summary>
        /// <param name="dataId"></param>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult DelBomSubDataById(string dataId,string userCode)
        { 
           rsl=new ReturnResult();
            try
            { 
                DbBomSub bms= new DbBomSub();
                bms.id =int.Parse(dataId);
                bms.isdel = 1;
                bms.delMsg = string.Format("{0}({1})",userCode,getNow());
                oper=new OperateModel();
                oper.Data= bms;
                oper.Types=OperateModel.OperateType.Edit;
                oper.Conditions = "id";
                rsl = cmd.Edit(oper);
            }
            catch(Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        
        public ReturnResult GetBgByBOM(string bomCode)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            try
            {
                if (string.IsNullOrWhiteSpace(bomCode))
                {
                    rsl.Message = "BOM编码不允许为空";
                    return rsl;
                }

                sb.Append("select s.bomCode,b.*,w.houseName wareHouseName,d.name statusName from bom_ProductionBom_sub s ");
                sb.Append("inner join fun_BanYang_list b  on b.bybarCode = s.materialCode and b.isdel=0 ");
                sb.Append("inner join fun_WareHouse_Info w on w.houseCode = b.wareHouse and w.isDel=0 ");
                sb.Append("inner join sys_dictionaries_info d on d.code=b.status and d.types='bst' and d.status=1 ");
                sb.Append("where s.isdel=0 and s.bomCode='" + bomCode + "'");
                var table = cmd.GetDataTable(sb.ToString());

                List<Dictionary<string, string>> dList = new List<Dictionary<string, string>>();
                if (table.Rows.Count > 0)
                {
                    foreach (DataRow dr in table.Rows)
                    {
                        var d = new Dictionary<string, string>();
                        d["bomCode"] = dr["bomCode"].ToString();
                        d["byCode"] = dr["byCode"].ToString();
                        d["byBarCode"] = dr["byBarCode"].ToString();
                        d["banchang"] = dr["banchang"].ToString();
                        d["banzhou"] = dr["banzhou"].ToString();
                        d["wareHouse"] = dr["wareHouse"].ToString();
                        d["wareHouseName"] = dr["wareHouseName"].ToString();
                        d["status"] = dr["status"].ToString();
                        d["statusName"] = dr["statusName"].ToString();
                        dList.Add(d);
                    }
                    rsl.Result = true;

                }
                rsl.Data = JsonConvert.SerializeObject(dList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;

        }

        /// <summary>
        /// 查询材料出库单信息
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <param name="baseCode"></param>
        /// <returns></returns>
        public ReturnResult Rdrecords11List(string pageIndex, string pageSize, string condition, string baseCode, ref string pageCount)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                #region 检索条件
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            //if (obj.Name == "sDate")
                            //{
                            //    sb.Append(" convert(datetime,dDate, 20)" + " >='" + obj.Value.ToString() + "' ");
                            //}
                            //else if (obj.Name == "eDate")
                            //{//结束时间
                            //    sb.Append(" convert(date,dDate, 20)" + "<= '" + obj.Value.ToString() + "' ");
                            //}
                            //else
                            //{
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            //}
                        }
                    }
                }
                #endregion
                
                var list = cmd.PageList("V_U8_Rdrecords11List", pageIndex, pageSize, sb.ToString(), "cInvCode", ref pageCount, "");
                //var list = cmd.PageTableList(tableName,pageIndex,pageSize,"","",ref pageCount,ref pageNumber);
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// bom删除
        /// </summary>
        /// <param name="bomCode"></param>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult DelBomInfoByCode(string bomCode,string userCode)
        { 
            rsl=new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(bomCode))
                {
                    rsl.Message = "BOM编码缺失";return rsl;
                }
                sb.Append("select id from pi_ProductionPlan_info where bomCode='"+ bomCode +"'");
                sb.Append(" and isdel=0");
                var pTable = cmd.GetDataTable(sb.ToString());
                if (pTable.Rows.Count > 0)
                {
                    rsl.Message = "BOM已被使用，系统禁止删除"; return rsl;
                }
                DbBomMain bomMain = new DbBomMain();
                bomMain.bomCode= bomCode;
                bomMain.isdel =1;
                bomMain.delMsg = string.Format("{0}({1})",userCode,getNow());
                oper = new OperateModel();
                oper.Data = bomMain;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "bomCode";
                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 版辊出入库记录信息
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="byCode"></param>
        /// <param name="baseCode"></param>
        /// <param name="pageCount"></param>
        /// <returns></returns>
        public ReturnResult BanGunInOutRecords(string pageIndex, string pageSize, string byCode, string baseCode, ref string pageCount)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("baseCode='"+ baseCode +"' and customCode='"+ byCode +"'");
                var list = cmd.PageList("V_BanYang_InOutRecords", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount, "");
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 删除样版/版辊信息
        /// </summary>
        /// <param name="byCode">版辊编码</param>
        /// <param name="userCode">人员账号</param>
        /// <returns></returns>
        public ReturnResult DelBanGun(string byCode,string userCode)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                //删除版辊信息
                DbBanGun dbBanGun = new DbBanGun();
                dbBanGun.byCode = byCode;
                oper = new OperateModel();
                oper.Data = dbBanGun;
                oper.Types = OperateModel.OperateType.Delete;
                oper.Conditions = "byCode";
                operList.Add(oper);


                DbBanYangPro db = new DbBanYangPro();
                db.byBarcode = byCode;
                oper = new OperateModel();
                oper.Data = db;
                oper.Types = OperateModel.OperateType.Delete;
                oper.Conditions = "byBarcode";
                operList.Add(oper);

                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        public ReturnResult GetWareData(string type)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(" select parValue from sys_parameters_info where parCode = 'work_warehouse_code' ");
                var ware = cmd.GetDataTable(sb.ToString()).Rows[0]["parValue"].ToString();
                var list = ware.Split(',');
                var workCode = "";
                for (int i = 0; i < list.Length; i++)
                {
                    workCode += "'" + list[i].ToString() + "',";
                }
                workCode = workCode.TrimEnd(',');
                sb.Clear();
                sb.Append("select houseCode cCode,houseName cName from fun_WareHouse_Info where");
                sb.Append(" isdel=0 and status='open' and houseCode in ("+ workCode + ") ");
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0)
                {
                    rsl.Data = cmd.TableToDictionary(table);
                    rsl.Result = true;
                }
                else
                {
                    rsl.Message = "没有数据";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 版辊板架号信息存储
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult SaveBanJia(string datas)
        {
            rsl = new ReturnResult();
            try
            {
                var obj =JsonConvert.DeserializeObject<JObject>(datas);
                string banjia = "";
                if (obj.Property("byBarCode") == null || string.IsNullOrWhiteSpace(obj["byBarCode"].ToString()))
                {
                    rsl.Message = "参数 byBarCode 不存在或值为空";
                    return rsl;
                }
                if (obj.Property("warePosition") != null && !string.IsNullOrWhiteSpace(obj["warePosition"].ToString()))
                {
                    banjia = obj["warePosition"].ToString();
                }
                DbBanGun by = new DbBanGun();
                by.byBarCode = obj["byBarCode"].ToString();
                by.warePosition = banjia;
                oper = new OperateModel();
                oper.Data= banjia;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "byBarCode";
                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            { 
            rsl.Message=ex.Message;
            }
            return rsl;
        }
    }
}
